import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../controllers/app_settings_controller.dart';
import '../../../config/app_branding.dart';
import '../../../routes/app_pages.dart';

class AppSettingsView extends GetView<AppSettingsController> {
  const AppSettingsView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: Container(
        decoration: BoxDecoration(
          gradient: AppBranding.primaryGradient,
        ),
        child: _buildBody(),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Text(
        '应用设置',
        style: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.w600,
          color: Colors.white,
        ),
      ),
      backgroundColor: Colors.transparent,
      elevation: 0,
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: AppBranding.primaryGradient,
        ),
      ),
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        children: [
          _buildAppInfoSection(),
          SizedBox(height: 20.h),
          // _buildThemeSection(),
          // SizedBox(height: 20.h),
          // _buildLanguageSection(),
          // SizedBox(height: 20.h),
          _buildDataSection(),
          SizedBox(height: 20.h),
          _buildNetworkSection(),
          SizedBox(height: 20.h),
          _buildAboutSection(),
        ],
      ),
    );
  }

  Widget _buildAppInfoSection() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Padding(
        padding: EdgeInsets.all(20.w),
        child: Column(
          children: [
            // 应用图标
            Container(
              width: 80.r,
              height: 80.r,
              decoration: BoxDecoration(
                gradient: AppBranding.primaryGradient,
                borderRadius: BorderRadius.circular(20.r),
                boxShadow: [
                  BoxShadow(
                    color: AppBranding.primaryColor.withOpacity(0.3),
                    blurRadius: 12,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Icon(
                Icons.auto_stories,
                size: 40.r,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 16.h),
            Text(
              AppBranding.appName,
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: const Color(0xFF333333),
              ),
            ),
            SizedBox(height: 8.h),
            Obx(() => Text(
                  '版本 ${controller.appVersion.value}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF666666),
                  ),
                )),
            SizedBox(height: 4.h),
            Text(
              AppBranding.appSlogan,
              style: TextStyle(
                fontSize: 12.sp,
                color: AppBranding.primaryColor,
                fontStyle: FontStyle.italic,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildThemeSection() {
    return _buildSection(
      title: '主题设置',
      icon: Icons.palette_outlined,
      children: [
        Obx(() => _buildSwitchTile(
              title: '深色模式',
              subtitle: '切换应用主题外观',
              icon: Icons.dark_mode_outlined,
              value: controller.isDarkMode.value,
              onChanged: controller.toggleTheme,
            )),
        _buildDivider(),
        _buildTile(
          title: '主题色彩',
          subtitle: '自定义应用配色方案',
          icon: Icons.color_lens_outlined,
          onTap: _showColorPicker,
        ),
      ],
    );
  }

  Widget _buildLanguageSection() {
    return _buildSection(
      title: '语言设置',
      icon: Icons.language_outlined,
      children: [
        Obx(() => _buildTile(
              title: '应用语言',
              subtitle: controller.currentLanguage.value,
              icon: Icons.translate_outlined,
              onTap: _showLanguageSelector,
            )),
      ],
    );
  }

  Widget _buildDataSection() {
    return _buildSection(
      title: '数据管理',
      icon: Icons.storage_outlined,
      children: [
        _buildTile(
          title: '收藏管理',
          subtitle: '查看和管理收藏内容',
          icon: Icons.favorite_outline,
          onTap: () => Get.toNamed(Routes.FAVORITES),
        ),
        _buildDivider(),
        _buildTile(
          title: '浏览历史',
          subtitle: '查看浏览记录',
          icon: Icons.history,
          onTap: () => Get.toNamed(Routes.HISTORY),
        ),
        _buildDivider(),
        _buildTile(
          title: '清除缓存',
          subtitle: '清理应用缓存数据',
          icon: Icons.cleaning_services_outlined,
          onTap: _showClearCacheDialog,
        ),
        _buildDivider(),
        _buildTile(
          title: '数据导出',
          subtitle: '导出收藏和历史记录',
          icon: Icons.file_download_outlined,
          onTap: controller.exportUserData,
        ),
      ],
    );
  }

  Widget _buildNetworkSection() {
    return _buildSection(
      title: '网络设置',
      icon: Icons.wifi_outlined,
      children: [
        _buildDivider(),
        Obx(() => _buildSwitchTile(
              title: '自动重连',
              subtitle: '网络断开时自动重新连接',
              icon: Icons.refresh_outlined,
              value: controller.autoReconnect.value,
              onChanged: controller.toggleAutoReconnect,
            )),
        _buildDivider(),
        _buildTile(
          title: '网络诊断',
          subtitle: '检测网络连接状态',
          icon: Icons.network_check_outlined,
          onTap: controller.runNetworkDiagnostics,
        ),
      ],
    );
  }

  Widget _buildAboutSection() {
    return _buildSection(
      title: '关于应用',
      icon: Icons.info_outline,
      children: [
        _buildTile(
          title: '用户协议',
          subtitle: '查看服务条款',
          icon: Icons.description_outlined,
          onTap: () => controller.openUserAgreement(),
        ),
        _buildDivider(),
        _buildTile(
          title: '隐私政策',
          subtitle: '了解隐私保护政策',
          icon: Icons.privacy_tip_outlined,
          onTap: () => controller.openPrivacyPolicy(),
        ),
        _buildDivider(),
        _buildTile(
          title: '意见反馈',
          subtitle: '提交建议和问题反馈',
          icon: Icons.feedback_outlined,
          onTap: controller.openFeedback,
        ),
        _buildDivider(),
        _buildTile(
          title: '检查更新',
          subtitle: '查看是否有新版本',
          icon: Icons.system_update_outlined,
          onTap: controller.checkForUpdates,
        ),
      ],
    );
  }

  Widget _buildSection({
    required String title,
    required IconData icon,
    required List<Widget> children,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                Container(
                  width: 32.r,
                  height: 32.r,
                  decoration: BoxDecoration(
                    gradient: AppBranding.secondaryGradient,
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Icon(
                    icon,
                    size: 18.r,
                    color: Colors.white,
                  ),
                ),
                SizedBox(width: 12.w),
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFF333333),
                  ),
                ),
              ],
            ),
          ),
          ...children,
        ],
      ),
    );
  }

  Widget _buildTile({
    required String title,
    required String subtitle,
    required IconData icon,
    required VoidCallback onTap,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Row(
            children: [
              Icon(
                icon,
                size: 24.r,
                color: const Color(0xFF666666),
              ),
              SizedBox(width: 16.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                        color: const Color(0xFF333333),
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0xFF999999),
                      ),
                    ),
                  ],
                ),
              ),
              Icon(
                Icons.chevron_right,
                size: 20.r,
                color: const Color(0xFF999999),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSwitchTile({
    required String title,
    required String subtitle,
    required IconData icon,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: Row(
        children: [
          Icon(
            icon,
            size: 24.r,
            color: const Color(0xFF666666),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 2.h),
                Text(
                  subtitle,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF999999),
                  ),
                ),
              ],
            ),
          ),
          Switch(
            value: value,
            onChanged: onChanged,
            activeColor: AppBranding.primaryColor,
          ),
        ],
      ),
    );
  }

  Widget _buildDivider() {
    return Divider(
      height: 1.h,
      thickness: 1,
      color: const Color(0xFFF0F0F0),
      indent: 56.w,
    );
  }

  void _showColorPicker() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择主题色'),
        content: SizedBox(
          width: 300.w,
          height: 200.h,
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
            ),
            itemCount: AppBranding.themeColors.length,
            itemBuilder: (context, index) {
              final color = AppBranding.themeColors[index];
              return GestureDetector(
                onTap: () {
                  controller.changeThemeColor(color);
                  Get.back();
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: color,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: Colors.grey.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showLanguageSelector() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择语言'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              title: const Text('简体中文'),
              onTap: () {
                controller.changeLanguage('zh_CN');
                Get.back();
              },
            ),
            ListTile(
              title: const Text('English'),
              onTap: () {
                controller.changeLanguage('en_US');
                Get.back();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showClearCacheDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('清除缓存'),
        content: const Text('确定要清除所有缓存数据吗？这将删除临时文件和图片缓存。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.clearCache();
            },
            child: const Text(
              '清除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }
}
